﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Security;
using Csla.Serialization;
using log4net;

namespace Sireass.Bl.Security
{
	[Serializable]
	public class SireassPrincipal : CslaPrincipal
	{
		// Create a logger for use in this class
		private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

		private SireassPrincipal(SireassIdentity identity)
			: base(identity)
		{ }

		public static void BeginLogin(string username, string password, Action<Exception> completed)
		{
			Sireass.Bl.Security.SireassIdentity.GetIdentity(username, password, (o, e) =>
		  {
			  if (e.Error != null)
				  Logout();
			  else
				  Csla.ApplicationContext.User = new SireassPrincipal(e.Object);
			  completed(e.Error);
		  });
		}

		public static void Login(string username, string password)
		{			
			var identity = Sireass.Bl.Security.SireassIdentity.GetIdentity(username, password);
			Csla.ApplicationContext.User = new SireassPrincipal(identity);
			if (log.IsDebugEnabled)
			{
				log.Debug("username: " + username);
				log.Debug("password: " + password);
				log.Debug("isAuthenticaded: " + identity.IsAuthenticated);
				if (identity.IsAuthenticated)
				{
					log.Debug("AuthenticationType: " + identity.AuthenticationType);
					log.Debug("Roles:");
					foreach (string role in identity.Roles)
					{
						log.Debug(role);
					}
				}
			}
		}

		public static void Load(string username)
		{
			var identity = Sireass.Bl.Security.SireassIdentity.GetIdentity(username);
			Csla.ApplicationContext.User = new SireassPrincipal(identity);
			if (log.IsDebugEnabled)
			{
				log.Debug("username: " + username);
				log.Debug("isAuthenticaded: " + identity.IsAuthenticated);
				if (identity.IsAuthenticated)
				{
					log.Debug("AuthenticationType: " + identity.AuthenticationType);
					log.Debug("Roles:");
					foreach (string role in identity.Roles)
					{
						log.Debug(role);
					}
				}
			}
		}

		public static void Logout()
		{
			Csla.ApplicationContext.User = new UnauthenticatedPrincipal();
		}
	}
}
